package com.ckmike.order_service.controller;

import com.ckmike.order_service.service.OrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * OrderController 简要描述
 * <p> TODO:描述该类职责 </p>
 *
 * @author ckmike
 * @version 1.0
 * @date 18-11-7 下午11:49
 * @copyright ckmike
 **/
@RestController
@RequestMapping("/api/v1/order")
@RefreshScope
public class OrderController {


    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("saveforribbon")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object saveforRibbon(@RequestParam("user_id") int userId, @RequestParam("product_id") int productId) {
        return this.orderService.saveForRibbon(userId, productId);
    }

    @RequestMapping("saveforfeign")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object saveforFeign(@RequestParam("user_id") int userId, @RequestParam("product_id") int productId) {
        return this.orderService.saveForFeign(userId, productId);
    }

    // 方法参数签名必须与api一致
    private Object saveOrderFail(int userId, int productId) {
        // 监控报警机制
        new Thread(() -> {
            String saveOrderKey = "save-order";
            String sendValue = redisTemplate.opsForValue().get(saveOrderKey);

            if (StringUtils.isBlank(sendValue)) {
                // 发送警告消息
                System.out.println("紧急消息，用户下单失败，请尽快处理查找原因.");
                redisTemplate.opsForValue().set(saveOrderKey, "save-order-fali", 30, TimeUnit.SECONDS);
            } else {
                System.out.println("已经发送消息，30秒内不可重复发送。");
            }
        }).start();

        Map<String, Object> fallbackResponse = new HashMap();
        fallbackResponse.put("code", -100);
        fallbackResponse.put("msg", "请求人数过多，请稍后再试。");
        return fallbackResponse;
    }
}
